package com.wwp.tbshop.view.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.wwp.tbshop.R;

/**
 * Created by QIANG on 2017/6/3.
 */

public class RatioLayout extends FrameLayout {

    private float mRatio;
    private int mode;

    private static final int RELATIV_WIDTH = 0;
    private static final int RELATIV_HEIGHT= 1;

    public RatioLayout(@NonNull Context context) {
        this(context, null);
    }

    public RatioLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        //获取自定义属性值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);
        mRatio = typedArray.getFloat(R.styleable.RatioLayout_Ratio, 0.5f);
        mode = typedArray.getInteger(R.styleable.RatioLayout_Relativ, RELATIV_WIDTH);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //测量宽高度,高度是由宽度决定的

        //取出宽度
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (mode == RELATIV_WIDTH) {     //竖屏,固定宽度
            //测量自己的孩子
            int childWidth = widthSize - getPaddingLeft() - getPaddingRight();
            int childHeight = (int) (childWidth / mRatio);
            measureChildren(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY));

            //设置自己最终的宽高
            setMeasuredDimension(widthSize, childHeight + getPaddingBottom() + getPaddingTop());
        } else if (mode == RELATIV_HEIGHT) {     //横屏,固定高度
            int childHeight = heightSize - getPaddingBottom() - getPaddingTop();
            int childWidth = (int) (childHeight * mRatio);
            measureChildren(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY));
            setMeasuredDimension(childWidth + getPaddingLeft() + getPaddingRight(), childHeight);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
